import json
from datetime import datetime

from django.core.paginator import Paginator
from django.http import JsonResponse
from django.views import View

from tree.models import *


# Create your views here.
# 查询所有数据
class ListView(View):
    def get(self, req):
        obj_list = Tree.objects.all().values()  # .values() 转成字典
        return JsonResponse({'code': 200, 'data': TreeSerializer(obj_list, many=True).data})  # 把外层的容器转为List后返回


# 样木选择集合：地址市->地址样地名称->树种->样木编号
class SelectView(View):
    def get(self, req):
        obj_list = TreeSerializer(Tree.objects.all(), many=True).data

        select_data = []
        unique_cities = list(set(item['address_city'] for item in obj_list))
        for city in unique_cities:
            city_data = [item for item in obj_list if item['address_city'] == city]

            children_city = []
            unique_area = list(set(item['address_name'] for item in city_data))
            for area in unique_area:
                area_data = [item for item in city_data if item['address_name'] == area]

                children_area = []
                unique_species = list(set(item['treeSpecies_name'] for item in area_data))

                for species in unique_species:
                    species_data = [item for item in area_data if item['treeSpecies_name'] == species]
                    children_species = []
                    for tree in species_data:
                        children_species.append({'value': tree['id'], 'label': tree['number']})
                    children_area.append(
                        {'value': species_data[0]['treeSpecies'], 'label': species, 'children': children_species})
                children_city.append({'value': area_data[0]['address'], 'label': area, 'children': children_area})
            select_data.append({'value': city_data[0]['address'], 'label': city, 'children': children_city})

        return JsonResponse({'code': 200, 'data': list(select_data)})  # 把外层的容器转为List后返回


# 信息查询
class SearchView(View):
    def post(self, req):
        data = json.loads(req.body.decode('utf-8'))
        pageNum = data['pageNum']  # 当前页
        pageSize = data['pageSize']  # 每页大小
        query = data['query']  # 查询参数

        # 获取查询集
        queryset = Tree.objects.filter(number__icontains=query)
        total = queryset.count()

        # 分页
        paginator = Paginator(queryset, pageSize)
        dataPage = paginator.page(pageNum)

        # 序列化数据 - 传递查询集给序列化器
        serializer = TreeSerializer(dataPage.object_list, many=True)

        # dataPage = Paginator(Tree.objects.filter(number__icontains=query), pageSize).page(pageNum)
        # # data = list(dataPage.object_list.values())  # 先转成字典，再转成列表
        # total = Tree.objects.filter(number__icontains=query).count()

        return JsonResponse({'code': 200, 'data': serializer.data, 'total': total})


class ActionView(View):
    # 根据id获取信息
    def get(self, req):
        obj = Tree.objects.get(id=req.GET.get('id'))
        return JsonResponse({'code': 200, 'data': TreeSerializer(obj).data})

    def delete(self, request):
        """
        删除操作
        :param request:
        :return:
        """
        idList = json.loads(request.body.decode("utf-8"))
        Tree.objects.filter(id__in=idList).delete()
        return JsonResponse({'code': 200})


# 新增或修改
class SaveView(View):
    def post(self, request):
        data = json.loads(request.body.decode('utf-8'))
        address = Address.objects.get(id=data['address'])
        treeSpecies = TreeSpecies.objects.get(id=data['treeSpecies'])
        if data['id'] == -1:  # 添加
            obj = Tree(address=address, year=data['year'], treeSpecies=treeSpecies,
                       number=data['number'], X=data['X'], Y=data['Y'],
                       TH=data['TH'], DBH=data['DBH'], DC=data['DC'], HFLB=data['HFLB'],
                       CW_SN=data['CW_SN'], CW_EW=data['CW_EW'], remark=data['remark'])
            obj.create_time = datetime.now().date()
            obj.save()
        else:  # 修改
            obj = Tree(id=data['id'], address=address, year=data['year'], treeSpecies=treeSpecies,
                       number=data['number'], X=data['X'], Y=data['Y'],
                       TH=data['TH'], DBH=data['DBH'], DC=data['DC'], HFLB=data['HFLB'],
                       CW_SN=data['CW_SN'], CW_EW=data['CW_EW'], remark=data['remark'])
            obj.update_time = datetime.now().date()
            obj.save()
        return JsonResponse({'code': 200, 'msg': '执行成功！'})


class StatusView(View):

    def post(self, req):
        data = json.loads(req.body.decode('utf-8'))
        obj = Tree.objects.get(id=data['id'])
        obj.status = data['status']
        obj.save()
        return JsonResponse({'code': 200, 'msg': '执行成功！'})
